import React, { useEffect } from 'react';

function append(content, container = 'content', tagname = 'p') {
  const tag = document.createElement(tagname);
  const text = document.createTextNode(content);
  tag.appendChild(text);
  document.getElementById(container).appendChild(tag);
}

function microtask() {
  const messageQueue = [];
  const sendMessage = message => {
    if (undefined === messageQueue[0]) {
      queueMicrotask(() => {
        const json = JSON.stringify(messageQueue);
        append(json);
      });
    }
    messageQueue.push(message);
  };

  sendMessage('刘备');
  sendMessage('关羽');
  sendMessage('张飞');
  sendMessage('赵云');
  sendMessage('马超');
  sendMessage('黄忠');
}

export default function Async() {
  useEffect(microtask, null);

  return (
    <div id="content">
      <p>微任务</p>
    </div>
  );
}
